import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import download from '@/utils/download';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Form, Spin, Tag, Table, Input, Button, message, Modal, Upload,Tooltip } from 'antd';
import styles from "./index.less";
import axios from 'axios';
import deleteimg from '@/assets/buttonimg/delete.png'
const FormItem = Form.Item;
const { TextArea } = Input;
const Search = Input.Search;
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_m18hmgbwet.js', // 在 iconfont.cn 上生成
});
import pen from '../../../assets/icons/bi.png';


class ThesaurusManage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      formatA: '',
      formatB: '',
      pageSize: 10,
      page: 1,
      value: '',
      total: 0,
      fileList: [],
      uploading: false,
    };
  }

  // eslint-disable-next-line react/sort-comp
  fetch = (query, page = 1, limit = 10) => {
    this.setState({ login: true })
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'thesaurusManage/fetch',
        payload: { robotId: currentUser.robotId, query, page, limit },
        callback: res => {
          console.log('数据', res);
          let temp = res.list
          temp.map((item, index) => item['key'] = index)
          this.setState({
            login: false,
            dataSource: temp,
            total: res.total
          })
        },
      });
    });
  }

  componentDidMount() {
    this.fetch()
  }

  lessdata = () => {
    const columns1 = [
      {
        title: <FormattedMessage id="app.customDictionary.core-word" defaultMessage="coreWord" />,
        width: 'calc(15vw)',
        dataIndex: 'word'
      },
      {
        title: <FormattedMessage id="app.customDictionary.core-agreed" defaultMessage="agreed" />,
        width: 'calc(75w)',
        dataIndex: 'aligns',
        render: aligns => (
          <span>
            {aligns.map((tag, index) => {
              let color = index % 2 == 1 ? '#87d3ac' : '#5092e1';
              return <Tag style={{ marginBottom: 2 }} color={color} key={tag}>{tag}</Tag>;
            })}
          </span>
        ),
      },
      {
        title: <FormattedMessage id="app.customDictionary.operation" defaultMessage="operation" />,
        dataIndex: 'sex',
        width: 'calc(10vw)',
        render: (text, item) => {
          return <div className={styles.pb}>
            <div
              className={styles.buttongl}
              onClick={(text) => { this.handleDeleteA(item) }}>
              {/* <MyIcon style={{ marginRight: 5 }} type="icon-bi" /> */}
              <img style={{ marginRight: 5 }} src={pen}></img>
              <span style={{ marginBottom: 1 }}><FormattedMessage id="app.customDictionary.edit" defaultMessage="Edit" /></span>
            </div>
            <div
              style={{ marginLeft: 10, background: '#e8313b' }}
              className={styles.buttongl}
              onClick={(text) => { this.fromDeletes(item) }}>
              <img  src={deleteimg} style={{ marginRight: 5 }} />
              <span style={{ marginBottom: 1 }}> <FormattedMessage id="app.customDictionary.out" defaultMessage="out" /></span>
            </div>
          </div>
        }
      }
    ]
    return (
      <Spin spinning=
      {this.state.login}>
        <Table
          // className='zdyTable'
          columns={columns1}
          dataSource={this.state.dataSource}// 数据
          onChange={this.handleChange}
          pagination={{  // 分页
            total: this.state.total,
            pageSize: this.state.pageSize,  // 显示几条一页
            current: this.state.page, // 当前页
            showSizeChanger: true,  // 是否显示可以设置几条一页的选项
            showQuickJumper: true,
            onChange: this.onChange,
            onShowSizeChange: this.onShowSizeChange
          }}

        />
      </Spin>
    )
  }

  handleDeleteA = (item) => {
    this.props.form.setFields({ "coreword": "" })
    this.props.form.setFields({ "synonym": "" })
    console.log('item', item)
    this.setState({
      formatC: item.word,
      formatA: item.word,
      formatB: item.aligns.join(','),
      showModel2: true
    })
  }

  fromDeletes = (item) => {
    console.log('item', item)
    Modal['confirm']({
      title: '删除任务',
      content: '确定删除吗？',
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'thesaurusManage/fetchc',
            payload: { robotId: currentUser.robotId, word: item.word },
            callback: res => {
              console.log('删除', res);
              this.fetch(this.state.value, this.state.page, this.state.pageSize)
              if (res.code === 0) {
                message.success(`${res.msg}`)
              } else {
                message['warning'](`${res.msg}`)
              }

            },
          });
        });
      },
      onCancel() {
        console.log('onCancel')
      }
    })
  }

  onChange = (val) => { // 页数选择
    console.log(val)
    this.setState({ page: val })
    this.fetch(this.state.value, val, this.state.pageSize)
  }


  onShowSizeChange = (val, pageSize) => {
    console.log(val, pageSize);
    this.fetch(this.state.value, val, pageSize)
    this.setState({ pageSize, page: val })
  }

  leadWay = () => {
    this.setState({ showModelA: true, fileList: [] })
  }


  impTemp = () => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'thesaurusManage/fetchd',
      payload: {},
      callback: (res) => {
        console.log(res.requestRes.headers)
        let filename = decodeURIComponent(res.requestRes.headers.get('Content-Disposition').split('=')[1]);
        download.byBlob(res.fileBlob, filename)
      }
    });

  }

  handleUpFile = (info) => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    fileList = fileList.map(file => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });
    if (fileList[0].size > 2000000) { // 2000000
      message.error('上传文件超出2M')
      this.setState({ fileList:[] });
    }else{
      this.setState({ fileList});
    }
  };

  uploadFile = (data) => {
    console.log(data)
    const robotId = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).robotId;
    const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token;
    axios.post('/cloud/new/basic/synonym/import', data, {
      method: 'post',
      processData: false,
      headers: { "Content-Type": "application/json", "token": token,"robotId":robotId }
    }).then((res) => {
      this.setState({
        uploading: false
      }, () => {
        if (res.data.code) {
          return message.error(res.data.msg)
        } else {
          this.setState({
            showModelA: false,
            visible: false,
            fileList: [],
            page:1
          }, () => {
            this.fetch()
            if (res.data.msg) {
              message.success(res.data.msg);
            } else {
              message.success('导入成功');
              
            }
          });

        }
      })
    }).catch((error) => {
      message.error('导入失败请稍等再试')
    });
  };


  businessWayA = () => {
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach(file => {
      console.log(file)
      formData.append('file', file.originFileObj);
    });
    this.setState({
      uploading: true
    });
    this.uploadFile(formData);
  }

  handleCancel = () => {
    this.setState({ showModelA: false, uploading: false, fileList: [] })
  }

  answerDetail = () => {
    // fetche
    const  {initialValue} = this.state
    if (this.state.total === 0) {
      message.error('空列表无法导出！')
    } else {
      const { dispatch, currentUser } = this.props;
      dispatch({
        type: 'thesaurusManage/fetche',
        payload: { query: initialValue },
        callback: (res) => {
          let filename = decodeURIComponent(res.requestRes.headers.get('Content-Disposition').split('=')[1]);
          download.byBlob(res.fileBlob, filename)
        }
      });
    }
   }


  render() {
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {// 文字
        xs: 24,
        sm: 4
      },
      wrapperCol: {// 输入框
        xs: 24,
        sm: 20
      }
    }
    const { uploading, fileList } = this.state;
    // const headData = { "token": JSON.parse(window.localStorage.getItem("currentUser")).token };
    const props = {
      // name: 'file',
      // headers: headData,
      // action: '/cloud/new/basic/synonym/import',
      // accept: '.xlsx',
      // onChange: this.handleChangeByUpload,
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      accept: '.xlsx',
      fileList,
      onChange: this.handleUpFile,
    }

   
    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <div className={styles.backgroundp}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10,color: '#4B5475', fontWeight: 600 }} xs={24}>
                <div className={styles.title}>
                  <span>同义词管理{`(${this.state.total})`}</span>
                  <span style={{ marginLeft: 2,paddingTop:2 }}>
                  <Tooltip
                    placement="top"
                    title="增加同义词是为了帮助机器人更好的识别聊天的问题描述，减少错别字、同义字、词、
                    句对机器人的影响，同时有效地减少类似句式同义句的编写。在这里添加的每一组同义词将在所有知识点中生效。
                    如库内有句子“我要办理易分期”，且已经把“医分期”设为“易分期”的同义词，当用户问“我要办理医分期”时，将会生效，回复正确答案。"
                    arrowPointAtCenter
                  >
                    <Icon type="info-circle" />
                  </Tooltip>
                </span>
                </div>
              </Col>
            </Row>
            <Card
              bordered={false}
            >
              <div className={styles.fromColumn}>
                {/* <Button type='primary' onClick={this.enumeration} icon="plus"><FormattedMessage id="app.customDictionary.add" defaultMessage="add" /></Button> */}
                <span className='buttonYs'><Button onClick={this.enumeration} icon="plus"><FormattedMessage id="app.customDictionary.add" defaultMessage="add" /></Button></span>
                <span  className='buttonYs'><Button onClick={this.leadWay} icon="arrow-down">导入</Button></span>
                <span  className='buttonYs'><Button onClick={this.answerDetail} icon="arrow-right">导出</Button></span>
                <span className={styles.right}>
                  {getFieldDecorator('coreword11', {
                    initialValue: this.state.value,
                  })(
                    <Search
                      // value={this.state.value}
                      placeholder="请输入搜索内容"
                      onSearch={value => {
                        console.log(value)
                        this.setState({ value })
                        if (value === '') {
                          this.fetch(value, this.state.page, this.state.pageSize)
                        } else {
                          this.setState({
                            page: 1
                          }, () => {
                            this.fetch(value, this.state.page, this.state.pageSize)
                          })

                        }


                      }}
                      style={{ width: 323 }}
                    />
                  )}

                </span>
              </div>
              {
                this.lessdata()
              }
            </Card>
            <Modal
              className='modelZdy'
              title='添加/编辑同义词'
              visible={this.state.showModel2}
              okText={<FormattedMessage id="app.customDictionary.save" />}
              cancelText={<FormattedMessage id="app.customDictionary.cancel" />}

              onCancel={() => {
                this.setState({
                  showModel2: false
                })
              }}
              onOk={this.coreWord}// 确定方法开出去
            >
              <Form layout="horizontal">
                <FormItem label={<FormattedMessage id="app.customDictionary.core-word" />} onSubmit={this.coreWord} {...FormItemLayont}>
                  {getFieldDecorator('coreword', {
                    initialValue: this.state.formatA,
                  })(
                    <Input />
                  )}

                </FormItem>
                <FormItem label={<FormattedMessage id="app.customDictionary.core-agreed" />} {...FormItemLayont}>
                  {getFieldDecorator('synonym', {
                    initialValue: this.state.formatB,
                  })(
                    <TextArea
                      placeholder="请输入同义词名称，可填写多个，请以中英文逗号分隔"
                      onPressEnter={this.coreWords}
                      autosize={
                        {
                          minRows: 4, maxRows: 6
                        }
                      }
                    />
                  )}
                </FormItem>
              </Form>
            </Modal>

            <Modal
              className='modelZdy'
              width={550}
              title='上传同义词'
              visible={this.state.showModelA}
              footer={[
                <Button key="back" onClick={this.handleCancel}>
                  取消
                </Button>,
                <Button key="submit" type="primary" loading={uploading} disabled={fileList.length === 0} onClick={this.businessWayA}>
                  {uploading ? '导入中' : '开始导入'}
                </Button>,
              ]}
              onCancel={() => {
                this.setState({ showModelA: false,uploading: false })
              }}
            >
              <Form layout="horizontal">
                <FormItem label='选择文件' onSubmit={this.coreWordOne} {...FormItemLayont}>
                  <Upload {...props} fileList={this.state.fileList}>
                    <Button >
                      <Icon type="upload" /> 选择文件
                        </Button>
                  </Upload>
                </FormItem>
                <FormItem label='上传规则' onSubmit={this.coreWordOne} {...FormItemLayont}>
                  <div className={styles.frame}>
                    <div><span>• 请按照模板中的示例格式进行编辑上传：</span> <span onClick={this.impTemp} className={styles.template}>下载xlsx模版</span></div>
                    <div><span>• 上传文件格式需要为“.xlsx”类型的Excel文件</span></div>
                    <div><span>• 导入的同义词数据将覆盖现有数据，请谨慎操作</span></div>
                  </div>
                </FormItem>
              </Form>
            </Modal>
          </div>
        </PageHeaderWrapper>
      </Suspense>
    );
  }

  coreWord = () => {
    this.setState({ value: '' })
    this.props.form.setFields({ "coreword11": "" })
    let userInfo = this.props.form.getFieldsValue();// 获取数据
    this.props.form.validateFields((err, values) => {// 校验方法formatA
      if (!err) {
        console.log(userInfo)
        if (userInfo.coreword !== '') {
          let ok = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(userInfo.coreword)
            var str = userInfo.synonym
            console.log(str)
            if (str) {
              var arr = new Array()
              arr = str.split(/[,，]/);
            }else{
              var arr = new Array()
            }
            // var arr = new Array()
            // arr = str.split(/[,，]/);
            console.log(arr)
            const { dispatch, currentUser } = this.props;
            this.reqRef = requestAnimationFrame(() => {
              dispatch({
                type: 'thesaurusManage/fetchb',
                payload: { aligns: arr, oldWord: this.state.formatA, word: userInfo.coreword, robotId: currentUser.robotId },
                callback: res => {
                  console.log('编辑', res);
                  if (res.code === 0) {
                    this.setState({
                      showModel2: false
                    })
                    this.props.form.setFields({ "coreword": "" })
                    this.props.form.setFields({ "synonym": "" })
                  } else {
                    message.success(`${res.msg}`)
                    this.setState({
                      showModel2: true
                    })
                  }
                  if (res.code === 0) {
                    message.success(`${res.msg}`)
                    console.log(this.state.page, this.state.pageSize)
                    this.fetch(this.state.value, this.state.page, this.state.pageSize)
                  } 
                },
              });
            });
         
        } else {
          message['warning'](`请添加核心词`)
        }

      }
    })
  }

  // 回车事件
  coreWords = e => {
    console.log(e.target.value)
    this.setState({ value: '' })
    this.props.form.setFields({ "coreword11": "" })
    let userInfo = this.props.form.getFieldsValue();// 获取数据
    this.props.form.validateFields((err, values) => {// 校验方法formatA
      if (!err) {
        console.log(userInfo)
        let ok = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(userInfo.coreword)
        console.log(ok)
        if (userInfo.coreword !== '') {
          if (ok) {
            var str = e.target.value
            console.log(str)
            var arr = new Array()
            arr = str.split(/[,，]/);
            console.log(arr)
            const { dispatch, currentUser } = this.props;
            this.reqRef = requestAnimationFrame(() => {
              dispatch({
                type: 'thesaurusManage/fetchb',
                payload: { aligns: arr, oldWord: this.state.formatA, word: userInfo.coreword, robotId: currentUser.robotId },
                callback: res => {
                  console.log('编辑', res);
                  if (res.code === 0) {
                    this.setState({
                      showModel2: true
                    })
                    this.props.form.setFields({ "coreword": "" })
                    this.props.form.setFields({ "synonym": "" })
                  } else {
                    this.setState({
                      showModel2: true
                    })
                  }
                  if (res.code === 0) {
                    message.success(`${res.msg}`)
                    console.log(this.state.page, this.state.pageSize)
                    this.fetch(this.state.value, this.state.page, this.state.pageSize)
                  }
                },
              });
            });
          } else { message['warning'](`同义词仅支持汉字、数字和字母 `) }
        } else {
          message['warning'](`请添加核心词`)
        }

      }
    })

  }



  enumeration = () => {
    this.props.form.setFields({ "coreword": "" })
    this.props.form.setFields({ "synonym": "" })
    this.setState({
      formatA: '',
      formatB: '',
      showModel2: true
    })
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(ThesaurusManage));
